package com.cskaoyan.controller.ad.admin;

import com.cskaoyan.bean.Ad;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.ListData;
import com.cskaoyan.bean.ad.CreateAdBO;
import com.cskaoyan.bean.ad.DeleteAdBO;
import com.cskaoyan.bean.ad.UpdateAdBO;
import com.cskaoyan.service.ad.admin.AdService;
import com.cskaoyan.tool.TestUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin/ad")
public class AdController {

    @Autowired
    AdService adService;

    @RequestMapping("/list")
    public BaseRespVo list(String page, String limit, String sort, String order,String name,String content){
        ListData<Ad> list = adService.list(page, limit, sort, order, name, content);
        return BaseRespVo.ok(list,"成功");
    }


    @RequestMapping("/create")
    @Transactional
    public BaseRespVo create(@RequestBody CreateAdBO createAdBO){
        boolean b1 = TestUrl.testUrlWithTimeOut(createAdBO.getLink(), 5000);
        if (! b1){
            return BaseRespVo.fail("url不可访问！请修改");
        }
        boolean b = adService.create(createAdBO);
        if (b){
            int lastInsertId = adService.getLastInsertId();
            Ad ad = adService.selectByPrimaryKey(lastInsertId);
            return BaseRespVo.ok(ad,"failed,try again ");
        } else {
            return BaseRespVo.fail("插入失败 请重试");
        }
    }

    @RequestMapping("delete")
    public BaseRespVo delete(@RequestBody DeleteAdBO deleteAdBO){
        boolean delete = adService.delete(deleteAdBO);
        if (delete){
            return BaseRespVo.ok();
        }else {
            return BaseRespVo.fail("delete failed，try again");
        }
    }


    /**
     *
     * @param updateAdBO
     * @return
     */
    @RequestMapping("update")
    @Transactional
    public BaseRespVo update(@RequestBody UpdateAdBO updateAdBO){
        boolean b = TestUrl.testUrlWithTimeOut(updateAdBO.getLink(), 5000);
        if (! b){
            return BaseRespVo.fail("url不可访问！请修改");
        }
        boolean update = adService.update(updateAdBO);
        if (update){
            return BaseRespVo.ok(updateAdBO,"成功");
        }else {
            return BaseRespVo.fail("update failed!try again");
        }
    }



}
